package cn.owen.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.owen.model.User;


/**
 * 管理当前当前登录对象
 * @author Burning
 * 2016-07-14
 */
public class CurrentUserUtils {
	private final String CUR_USER = "cur_user";//后台用户
	private final String CUR_ACCOUNT="cur_account";//前台登录用户信息
	private final String CUR_USER_TYPE="0";//用户类型 0后台 1前台
	public static CurrentUserUtils INSTANCE = null;
	
	private CurrentUserUtils(){
		
	}
	
	/**
	 * 获取实例
	 * @return
	 */
	public static CurrentUserUtils getInstance(){
		if(INSTANCE == null){
			synchronized (CurrentUserUtils.class) {
				if(INSTANCE == null) {
					INSTANCE = new CurrentUserUtils();
				}
			}
		}
		
		return INSTANCE;
	}
	/**
	 * 获取当前Request
	 * @return
	 */
	private HttpServletRequest getRequest() {  
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();  
        return requestAttributes.getRequest();  
    } 
	
	/**
	 * 获取当前Session
	 * @return
	 */
	private HttpSession getSession() {  
        return getRequest().getSession(true);  
    }
	
	/**
	 * 获取当前session里面放置的User对象
	 * @return
	 */
	public User getUser(){
		return (User)getSession().getAttribute(CUR_USER);
	}
	
	/**
	 * 把当前User对象放置到session里面
	 * @param user
	 */
	public void setUser(User user){
		getSession().setAttribute(CUR_USER, user);
		getSession().setAttribute(CUR_USER_TYPE, "0");
	}
	 /**
	 * 把当前Account对象放置到session里面
	 * @param account
	 *//*
	public void setAccount(TAccount account){
		getSession().setAttribute(CUR_ACCOUNT, account);
		if(account!=null){
			User user=new User();
			user.setId(0);
			user.setName(account.getEmail());
			getSession().setAttribute(CUR_USER, user);
			getSession().setAttribute(CUR_USER_TYPE, "1");
		}else{
			getSession().setAttribute(CUR_USER, null);
			getSession().setAttribute(CUR_USER_TYPE, null);
		}
		
	}*/
	/**
	 * 获取当前session里account对象
	 * @return
	 */
	/*public TAccount getAccount(){
		return (TAccount)getSession().getAttribute(CUR_ACCOUNT);
	}
	
	public static void forceAccountLogout(Integer accountId)  
    {  
        if(SessionListener.sessionMap.get( accountId ) != null)  
        {  
            HttpSession session = SessionListener.sessionMap.get( accountId );  
  
            SessionListener.sessionMap.remove( accountId );  
  
            Enumeration e = session.getAttributeNames();  
  
            while(e.hasMoreElements())  
            {  
                String sessionName = (String) e.nextElement();  
  
                session.removeAttribute( sessionName );  
            }  
  
            session.invalidate();  
        }  
    }  */
}
